package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebFilter(value = "wmTokenFilter",urlPatterns = "/**")
@Component //被spring扫描的类
@Slf4j
public class WmTokenFilter extends GenericFilter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取请求头中的userId的值，threadlocal中保存的用户信息
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String userId = request.getHeader("userId");
        //打印日子
        log.info("当前用户的信息：{}",userId);
        //2.如果userId中有值，就价格登录用户的信息放到threadlocal中进行保存
        if (StringUtils.isNotBlank(userId)){
            //2.1创建WmUser类对象
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            //2.2利用工具类将用户保存到threadlocal中
            WmThreadLocalUtils.setUser(wmUser);
        }
        //3.放行请求
        filterChain.doFilter(servletRequest,servletResponse);
        //4.清空threadlocal中的用户信息，目的是避免下一个不登录的用户拿到上一个的用户信息来进行登录
        WmThreadLocalUtils.clear();
    }
}
